<?php

namespace app\api\controller;

use app\BaseController;
use WebSocket\Client;
require root_path().'vendor/autoload.php';

class GetAppKey extends BaseController
{
    public function index()
    {
//        phpinfo();
        $mess = $this->request->param('mess/s');
        $addr = "wss://spark-api.xf-yun.com/v3.1/chat";
        $Appid = "28e8c18a";
        $Apikey = "0d1e2aa0ce7502cbfb740c1d04639a21";
        $ApiSecret = "N2RlOTMwNWRhZWFkNTZkODcwNDdkNzcw";

        $authUrl = $this->assembleAuthUrl("GET", $addr, $Apikey, $ApiSecret);
        $client = new Client($authUrl);

        if ($client) {
            $data = $this->getBody($Appid, $mess);
            $client->send($data);
            $answer = "";
            while (true) {
                $response = $client->receive();
                $resp = json_decode($response, true);
                $code = $resp["header"]["code"];
                $resp = json_decode($response, true);
                $code = $resp["header"]["code"];
                echo $resp['payload']['choices']['text'][0]['content'];
                if (0 == $code) {
                    $status = $resp["header"]["status"];
                    if ($status != 2) {
                        $content = $resp['payload']['choices']['text'][0]['content'];
                        $answer .= $content;
                    } else {
                        $content = $resp['payload']['choices']['text'][0]['content'];
                        $answer .= $content;
                        $total_tokens = $resp['payload']['usage']['text']['total_tokens'];
                        break;
                    }
                } else {
                    echo "服务返回报错" . $response;
                    break;
                }
            }
        } else {
            echo "无法连接到 WebSocket 服务器";
        }
    }

    // 发送post请求
    function http_request($url, $post_data, $headers)
    {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => $headers,
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

//        echo $result;

        return "success";
    }

    // 构造参数体
    function getBody($appid, $question)
    {
        $header = array(
            "app_id" => $appid,
            "uid" => "12345"
        );

        $parameter = array(
            "chat" => array(
                "domain" => "generalv3",
                "temperature" => 0.5,
                "max_tokens" => 1024
            )
        );

        $payload = array(
            "message" => array(
                "text" => array(
                    array("role" => "user", "content" => $question)
                )
            )
        );

        $json_string = json_encode(array(
            "header" => $header,
            "parameter" => $parameter,
            "payload" => $payload
        ));

        return $json_string;
    }

    // 鉴权方法
    function assembleAuthUrl($method, $addr, $apiKey, $apiSecret)
    {
        if ($apiKey == "" && $apiSecret == "") { // 不鉴权
            return $addr;
        }

        $ul = parse_url($addr); // 解析地址
        if ($ul === false) { // 地址不对，也不鉴权
            return $addr;
        }

        $timestamp = time();
        $rfc1123_format = gmdate("D, d M Y H:i:s \G\M\T", $timestamp);

        $signString = array("host: " . $ul["host"], "date: " . $rfc1123_format, $method . " " . $ul["path"] . " HTTP/1.1");

        $sgin = implode("\n", $signString);
//        print($sgin);

        $sha = hash_hmac('sha256', $sgin, $apiSecret, true);
//        print("signature_sha:\n");
//        print($sha);
        $signature_sha_base64 = base64_encode($sha);

        $authUrl = "api_key=\"$apiKey\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"$signature_sha_base64\"";

        $authAddr = $addr . '?' . http_build_query(array(
                'host' => $ul['host'],
                'date' => $rfc1123_format,
                'authorization' => base64_encode($authUrl),
            ));

        return $authAddr;
    }
}
